<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/7/4
 * Time: 1:31 PM
 */
namespace app\backend\modules\business\services;

use app\common\exceptions\BizException;
use app\common\models\Department;
use app\common\models\DepartmentAdminUser;
use Illuminate\Support\Facades\DB;
use Exception;


class DepartmentService
{
    public function getList($params){
        $pid = $params['pid'];
        $query = Department::site()->select();
        if ($pid) {
            $parentDepartment = Department::site()->find($pid);
            if (!$parentDepartment) {
                throw new BizException('部门不存在');
            }
            $query = $query->where('level', '>', $parentDepartment->level);
        }
        /*if($params['name']){
            $query->where('name','like','%'.$params['name'].'%');
        }*/

        $departmentList = $query
            ->orderBy('display_order', 'desc')
            ->orderBy('id', 'asc')
            ->get();

        $res = [];
        $userCounts = DepartmentAdminUser::site()->select(DB::raw('COUNT(distinct uid) as count'), 'department_id')->groupBy('department_id')->get()->toArray();
        $userCounts = array_column($userCounts, 'count', 'department_id');
        if($parentDepartment){
            $res[] = $parentDepartment->toArray();
        }elseif ($departmentList->isNotEmpty()){
            $res = $departmentList->where('level', 1)->values()->toArray();
        }

        $departmentList = $departmentList->toArray();
        foreach ($res as $k => $v) {
            $res[$k]['user_count'] = $userCounts[$v['id']] ?: 0;
            //$v['parent_name'] = $parent_name;
            $res[$k]['sub_departments'] = self::loopSubDepartment($departmentList, $v['id'],$userCounts);
        }

        return $res;
    }

    /*
    * 递归获取部门列表下级（不使用集合，很慢）
    */
    public static function loopSubDepartment(&$departmentList, $id,$userCounts)
    {
        $res = [];
        foreach ($departmentList as $k => $v) {
            if ($v['pid'] == $id) {
                unset($departmentList[$k]);
                $v['parent_name'] = $v['name'];
                $v['sub_departments'] = static::loopSubDepartment($departmentList, $v['id'],$userCounts);
                if (empty($v['sub_departments'])) {
                    unset($v['sub_departments']);
                }
                $res[] = $v;
            }
        }

        return $res;
    }
    /*
     * 创建/编辑部门
     */
    public function changeDepartment($name, $pid = 0, $id = 0, $order = 0)
    {

        DB::beginTransaction();

        try {

            if ($pid) {
                $parentDepartment = Department::site()->find($pid);
                if (!$parentDepartment) {
                    throw new BizException('上级部门不存在');
                }
            } else {
                if (!$id && Department::site()->where('level', 1)->first()) {
                    throw new BizException('一级部门只允许存在一个');
                }
            }
            $updateData = [
                'name' => $name,
                'pid' => $pid,
                'level' => $parentDepartment ? $parentDepartment->level + 1 : 1,
            ];

            if (!$id) {

                if (Department::where($updateData)->first()) {
                    throw new BizException('同一部门下不能存在名称相同的部门');
                }

                $updateData['display_order'] = intval($order) ?: 0;
                $updateData['site_id'] = \YunCms::siteId();
                $department = Department::create($updateData);
                if (!$department) {
                    throw new BizException('创建部门失败');
                }
            } else {
                $department = Department::site()->find($id);
                if (!$department) {
                    throw new BizException('部门不存在');
                }
                if (intval($order)){
                    $updateData['display_order'] = intval($order);
                }
                $department->fill($updateData);
                $department->save();
            }
        } catch (Exception $e) {
            DB::rollBack();
            throw new BizException($e->getMessage());
        }
        DB::commit();
    }
    /*
    * 删除部门
    */
    public static function deleteDepartment($id)
    {

        DB::beginTransaction();

        try {
            $department = Department::site()->find($id);
            if (!$department) {
                throw new BizException('部门不存在');
            }

            if ($department->level == 1) {
                throw new BizException('一级部门不允许删除');
            }
            $subDepartmentId = Department::getAllDepartmentSubId([$department->id]);
            if ($subDepartmentId) {
                throw new BizException('请先删除下级部门');
            }
            $departmentAdminUser = DepartmentAdminUser::where('department_id', $department->id)->first();
            if ($departmentAdminUser) {
                throw new BizException('请先移除该部门的员工');
            }

            if (!$department->delete()) {
                throw new BizException('部门删除失败');
            }
        } catch (Exception $e) {
            DB::rollBack();
            throw new BizException($e->getMessage());
        }

        DB::commit();

    }
}